package com.innovation.ic.cc.web.schedule;

import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.cc.base.model.cc.erp9_pvebcs.ErpDictionaries;
import com.innovation.ic.cc.base.pojo.enums.ImportEnumerationEnum;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.vo.DictionariesVo;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 同步erp,部分字典数据,和我的公司
 */
@Component
@Slf4j
public class importEnumerationJobSchedule extends AbstractSchedule {

    @XxlJob("importEnumerationJob")
    private void importEnumerationJob() {
        try {
            String jobParam = XxlJobHelper.getJobParam();
            XxlJobHelper.log("拿到执行器参数 {} ", jobParam);
            ServiceResult<List<ErpDictionaries>> erpDictionaries = super.erpDictionariesService.findErpDictionaries(ImportEnumerationEnum.COMPANY_TYPE);
            if (erpDictionaries == null || CollectionUtils.isEmpty(erpDictionaries.getResult())) {
                return;
            }
            List<ErpDictionaries> erpDictionariesList = erpDictionaries.getResult();
            log.info("importEnumerationJob 拿到erp得返回结果 : {}", JSONObject.toJSONString(erpDictionariesList));
            if (erpDictionariesList == null || erpDictionariesList.size() == 0) {
                return;
            }
            super.dictionariesService.saveBatch(this.bindDictionaries(erpDictionariesList));
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            log.error("同步erp我的公司枚举错误", e);
            XxlJobHelper.handleFail();
        }
    }

    /**
     * 绑定字典参数
     *
     * @param erpDictionariesList
     * @return
     */
    public List<DictionariesVo> bindDictionaries(List<ErpDictionaries> erpDictionariesList) {
        List<DictionariesVo> result = new ArrayList<>();
        for (ErpDictionaries erpDictionaries : erpDictionariesList) {
            DictionariesVo dictionariesVo = new DictionariesVo();
            dictionariesVo.setCreateDate(new Date());
            dictionariesVo.setDCode(erpDictionaries.getDCode());
            dictionariesVo.setDName(erpDictionaries.getDName());
            dictionariesVo.setId(erpDictionaries.getExternalAllyId());
            dictionariesVo.setDTypeId(erpDictionaries.getId());
            dictionariesVo.setDValue(erpDictionaries.getDValue());
            result.add(dictionariesVo);
        }
        return result;
    }
}